﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RestSharp;
using System.Text;

namespace tDonkeySite.Controllers
{
    public class CoursesController : Controller
    {
        Dictionary<string, int> days = new Dictionary<string, int>(){
            {"א",0},
            {"ב",1},
            {"ג",2},
            {"ד",3},
            {"ה",4},
            {"ו",5},
        };

        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(string number = "", string name = "", string points = "",
                                  string startTime = "", string endTime = "", string day = "",
                                  string teacherFirstName = "", string teacherLastName = "",
                                  string[] faculty = null, bool sameWord = true,
                                  string examDate="", string term="A",
                                  int page = 1, int count=25)
        {

            if (number == "" && name == "" && points == ""
                && teacherFirstName == "" && teacherLastName == "" &&
                examDate == "" &&
                (faculty == null || faculty.Length == 0))
            {
                return View();
            }

            var client = new RestClient("http://tdonekyapi.yudapps.com/");
            //var client = new RestClient("http://localhost:45312/");
            var request = new RestRequest("api/Courses/", Method.GET);
            request.RequestFormat = DataFormat.Json;
            request.AddParameter("temp", 0);
            if (string.IsNullOrEmpty(number))
                number = "0";
            request.AddParameter("number", number);
            if (!string.IsNullOrEmpty(name))
                request.AddParameter("name", name);
            if (!string.IsNullOrEmpty(points))
                request.AddParameter("points", points);
            if (!string.IsNullOrEmpty(startTime))
                request.AddParameter("startTime", startTime);
            if (!string.IsNullOrEmpty(endTime))
                request.AddParameter("endTime", endTime);
            if (!string.IsNullOrEmpty(day))
                request.AddParameter("day", day);
            if (!string.IsNullOrEmpty(teacherFirstName))
                request.AddParameter("teacherFirstName", teacherFirstName);
            if (!string.IsNullOrEmpty(teacherLastName))
                request.AddParameter("teacherLastName", teacherLastName);
            if (!string.IsNullOrEmpty(examDate))
            {
                /*Change the format of the exam date from 07/10/2014 to 7/14/0010. 
                We must find a more nice way to search for exam dates.
                The mean problem is in the way we save the dates in the database*/
                char[] delimiter = {'/'};
                string month = examDate.Split(delimiter)[0];
                month = Convert.ToInt32(month).ToString(); //This double conversion will remove 0 from 07
                string d = examDate.Split(delimiter)[1];
                //d = Convert.ToInt32(d).ToString();
                //string y = examDate.Split(delimiter)[2];
                //y = "14";//Convert.ToInt32(y).ToString();
                examDate = month + "/14/" + "00" + d;   //TODO: you must not add hardcode year!!!
                request.AddParameter("examDate", examDate);
                request.AddParameter("term", term);
            }
            request.AddParameter("page", page);
            request.AddParameter("count", count);
            if (faculty != null)
            {
                foreach (string f in faculty)
                {
                    request.AddParameter("faculty", f);
                }
            }
            request.AddParameter("sameWord", sameWord.ToString());

            IRestResponse<List<eDonkeyClassLibrary.Course>> response = client.Execute<List<eDonkeyClassLibrary.Course>>(request);
            if (response == null || response.Data == null || response.Data.Count == 0)
            {
                ViewBag.Message = "Your search did not match any courses.";
                return View();
            }
            ViewBag.Courses = response.Data;
            return View();
        }
        
        public ActionResult Info(string number)
        {
            if (!string.IsNullOrEmpty(number))
            {
                var client = new RestClient("http://tdonekyapi.yudapps.com/");
                //var client = new RestClient("http://localhost:45312/");
                var request = new RestRequest("api/Courses/", Method.GET);
                request.RequestFormat = DataFormat.Json;
                request.AddParameter("temp", 0);
                request.AddParameter("number", number);
                IRestResponse<List<eDonkeyClassLibrary.Course>> response = client.Execute<List<eDonkeyClassLibrary.Course>>(request);
                ViewBag.Name = response.Data[0].Name;
                ViewBag.Number = response.Data[0].Number;
                ViewBag.Points = response.Data[0].Points;
                //TODO: The dates saved in the database is not in the correct order:
                ViewBag.TermA = response.Data[0].TermA.Value.Year.ToString() + "/" + response.Data[0].TermA.Value.Month.ToString();
                ViewBag.TermB = response.Data[0].TermB.Value.Year.ToString() + "/" + response.Data[0].TermB.Value.Month.ToString();

                ViewBag.Faculty = response.Data[0].Faculty;
                ViewBag.Notes = response.Data[0].Notes;

                ViewBag.LecturerInCharge = response.Data[0].Teacher.FirstName + " " + response.Data[0].Teacher.LastName;
                ViewBag.Groups = response.Data[0].Groups;
                ViewBag.link = "/Courses/Select/?number=" + response.Data[0].Number +
                               "&name=" + response.Data[0].Name.Replace(" ", "%20") + "&points=" + response.Data[0].Points;
            }
            return View();
        }

        public ActionResult MyGroups()
        {
            //var client = new RestClient("http://tdonekyapi.yudapps.com/");
            var client = new RestClient("http://localhost:45312/");
            var request = new RestRequest("api/Courses/MyGroups", Method.GET);
            request.RequestFormat = DataFormat.Json;
            foreach (string c in this.ControllerContext.HttpContext.Request.Cookies["Courses"].Values.AllKeys)
            {
                request.AddParameter("courses", c);
            }
            IRestResponse<List<eDonkeyClassLibrary.Group>> response = client.Execute<List<eDonkeyClassLibrary.Group>>(request);
            if (response == null || response.Data == null || response.Data.Count == 0)
            {
                var emptyObj = new object[1];
                return Json(new { emptyObj, count = 0 }, null, JsonRequestBehavior.AllowGet);
            }
            List<eDonkeyClassLibrary.Group> groups = response.Data;
            var jsonGroups = new object[groups.Count];
            for(int i=0; i < groups.Count; i++)
            {
                jsonGroups[i] = new
                {
                    cname = groups[i].Course.Name,
                    cnum = groups[i].Course.Number,
                    gnum = groups[i].Number.ToString(),
                    gid = groups[i].Id.ToString(),
                    r = groups[i].Role,
                    day = days[groups[i].PlaceTimes[0].Day.Trim()].ToString(),
                    start = groups[i].PlaceTimes[0].StartTime.Trim(),
                    duration = groups[i].PlaceTimes[0].Duration.Trim()
                };                             
            }
            return Json(new { jsonGroups, count = groups.Count }, null, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Select(string number = "", string name = "", double points = 0)
        {
            if (number == "")
            {
                if (!this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Courses"))
                {
                    return View();
                }
                else
                {
                    ViewBag.SelectedCourses = this.ControllerContext.HttpContext.Request.Cookies["Courses"].Values;
                    return View();
                }
            }

            System.Web.HttpCookie myCookie;
            if (!this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Courses"))
            {
                myCookie = new System.Web.HttpCookie("Courses");
                myCookie.Expires = DateTime.Now.AddDays(1d);
                this.ControllerContext.HttpContext.Response.Cookies.Add(myCookie);
            }
            myCookie = this.ControllerContext.HttpContext.Request.Cookies["Courses"];
            
            if (myCookie.Values.Get(number) != null)
            {
                ViewBag.Message = "Already selected";
            }
            else
            {
                myCookie.Values.Add(number, Server.UrlEncode(name) + "$" + points.ToString());
                this.ControllerContext.HttpContext.Response.Cookies.Add(myCookie);
                ViewBag.Message = "Saved Successfully";
            }
            ViewBag.SelectedCourses = myCookie.Values;
            return View();
        }

        public ActionResult Unselect(string number = "")
        {
            if (number == "" ||
                !this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Courses"))
            {
                return View("Select");
            }
            System.Web.HttpCookie myCookie = this.ControllerContext.HttpContext.Request.Cookies["Courses"];

            if (myCookie.Values.Get(number) != null)
            {
                myCookie.Values.Remove(number);
                if (myCookie.Values.Count == 0)
                {
                    //When user unselect his courses, remove the cookie!
                    myCookie.Expires = DateTime.Now.AddDays(-1d);
                }
                this.ControllerContext.HttpContext.Response.Cookies.Add(myCookie);
            }
            ViewBag.SelectedCourses = myCookie.Values;
            return View("Select");
        }

        public ActionResult GetFaculty(string name = "")
        {
            var client = new RestClient("http://tdonekyapi.yudapps.com/");
            //var client = new RestClient("http://localhost:45312/");
            var request = new RestRequest("api/Courses/Faculty", Method.GET);
            request.RequestFormat = DataFormat.Json;

            IRestResponse<List<string>> response = client.Execute<List<string>>(request);
            if (response == null || response.Data == null)
            {
                return View();
            }

            int length = response.Data.Count;
            var facultiesJsonList = new object[length];
            for (int i = 0; i < length; ++i)
            {
                facultiesJsonList[i] = new { name = response.Data[i] };
            }
            return Json(new { facultiesJsonList, length }, null, JsonRequestBehavior.AllowGet);
        }
    }
}
